package com.macrohard.admin.controller;

import cn.dev33.satoken.stp.SaLoginConfig;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.macrohard.admin.domain.UserInfo;
import com.macrohard.admin.dto.UserDTO;
import com.macrohard.admin.service.SysMenuService;
import com.macrohard.admin.service.TeacherService;
import com.macrohard.common.base.response.R;
import com.macrohard.mapper.domain.SysMenu;
import com.macrohard.mapper.domain.Teacher;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@RestController
@RequiredArgsConstructor
@Validated
@RequestMapping("user")
@Api(tags = "用户接口")
public class UserController {

	private final TeacherService teacherService;
	private final SysMenuService menuService;

	@PostMapping("login")
	@ApiOperation("登录接口")
	public R doLogin(@RequestBody UserDTO user) {
		if (Objects.isNull(user.getId()) || Objects.isNull(user.getPassword())) {
			return R.error(500, "登录失败, 教师工号或密码不能为空");
		}
		Teacher teacherByName = teacherService.getOne(new LambdaQueryWrapper<Teacher>().eq(Teacher::gettTeacherid, user.getId()));
		if(Objects.isNull(teacherByName)) {
			return R.error(500, "登录失败, 用户不存在");
		}
		if (!teacherByName.gettPassword().equals(SecureUtil.md5(user.getPassword()))) {
			return R.error(500, "登录失败, 密码错误");
		}
		StpUtil.login(teacherByName.gettTeacherid(), SaLoginConfig.setExtra("teacherId", teacherByName.gettTeacherid()));
		Map<String, Object> result = new HashMap<>();
		result.put("token", StpUtil.getTokenValue());
		return R.ok("登录成功", result);
	}

	@PostMapping("logout")
	@ApiOperation("退出登录")
	public R logout() {
		StpUtil.logout();
		return R.ok("注销成功");
	}

	@GetMapping("info")
	@ApiOperation("获取登录信息")
	public R info() {
		String loginId = (String) StpUtil.getLoginId();
		LambdaQueryWrapper<Teacher> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(Teacher::gettTeacherid, loginId);
		Teacher one = teacherService.getOne(queryWrapper);
		List<String> paths = menuService.getMenuWithTeacherRole(one.gettId(), true).stream().map(SysMenu::getName).collect(Collectors.toList());
		UserInfo userInfo = new UserInfo();
		userInfo.setUserid(one.gettTeacherid());
		userInfo.setName(one.gettName());
		userInfo.setAvatar(one.gettPicture());
		userInfo.setEmail(one.gettEmail());
		userInfo.setPerm(paths);
		return R.ok("ok", userInfo);
	}

	@GetMapping("isLogin")
	@ApiOperation("检测是否登录")
	public R isLogin() {
		Map<String, Object> result = new HashMap<>();
		result.put("isLogin", StpUtil.isLogin());
		return R.ok("操作成功", result);
	}
}
